package security

import (
	"path/filepath"
	"strings"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"os"
	"io/ioutil"
	"log"
)

func CheckSignature(signature, content, keyPath string)  (isOk bool, message string) {
	keyFile := filepath.Join(keyPath, "signature.key")
	msg := ""
	if fileExist(keyFile) {
		key := string(readFile(keyFile))
		key = strings.TrimSpace(key)
		rightSignature := hash256Hmac(content, key)
		isRight := rightSignature == signature
		if !isRight {
			msg = "秘钥错误! HASH256 HMAC 结果: "+ rightSignature
		}
		return isRight, msg
	}
	msg = "工作目录中, 秘钥文件 "+ keyFile +" 不存在!"
	return  false, msg
}



func hash256Hmac(message string, secret string) string {
	key := []byte(secret)
	h := hmac.New(sha256.New, key)
	h.Write([]byte(message))
	md := h.Sum(nil)
	return hex.EncodeToString(md)
}

func fileExist(filepath string) bool {
	if _, err := os.Stat(filepath); os.IsNotExist(err) {
		return false
	}
	return true
}


func readFile(filename string) []byte {
	b, err := ioutil.ReadFile(filename)
	checkError(err)
	return b
}


func checkError(err error) {
	if err != nil {
		log.Fatal("fatal error: " + err.Error())
	}
}